package org.huzhp.gateway.dynamic.route;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @Description: 动态路由接口
 * @Author: huzp
 * @CreateDate: 2020/3/12 13:31
 * @Version: 1.0
 */
@RestController
@RequestMapping("/gateway/route")
public class RouteController {
    @Autowired
    private DynamicRouteService dynamicRouteService;


    //获取路由
    @GetMapping
    public Flux<RouteDefinition> get() {
        return dynamicRouteService.getRoutes();
    }

    //增加路由
    @PostMapping
    public Mono<ResponseEntity<Object>> add(@RequestBody GatewayRouteDefinition definition) {

        try {
            this.dynamicRouteService.add(definition.build());
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
        return Mono.just(ResponseEntity.ok().build());
    }

    //删除路由
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
        try {
            return this.dynamicRouteService.delete(id);
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
    }

    //更新路由
    @PutMapping
    public Mono<ResponseEntity<Object>> update(@RequestBody GatewayRouteDefinition definition) {
        try {
            this.dynamicRouteService.update(definition.build());
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
        return Mono.just(ResponseEntity.ok().build());
    }


}
